<?php
class Crypt_HMAC{
    private $_func;
    private $_ipad;
    private $_opad;

    public function __construct($key, $method="md5"){
        if(!in_array($method, array('sha1', 'md5'))){
            die('Unsupported hash function'. $method);
        }
        $this->_func = $method;
        $keylen = strlen($key);
        if($keylen > 64){
            $key = pack("H32", $method($key));
        }

        if($keylen < 64){
            $key = str_pad($key, 64, chr(0));
        }

        $this->_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36),64);
        $this->_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5C),64);
    }

    public function hash($data){
        $func = $this->_func;
        $inner = pack('H32', $func($this->_ipad.$data));
        $digest = $func($this->_opad. $inner);
        return $digest;
    }
}

define("SECRET_KEY", 'Professional PHP 5 Programming Exampe');

function create_parameters($array){
    $data ='';
    $ret = array();
    foreach($array as $key => $value){
        $data .= $key . $value;
        $ret[] = "$key=$value";
    }
    $h = new Crypt_HMAC(SECRET_KEY, 'sha1');
    $hash = $h->hash($data);
    $ret[] = "hash=$hash";
    return implode('&amp;', $ret);
}
echo '<a href="script.php?'.create_parameters(array('cause'=>'vars')).'">err!</a>';

function verify_parameters($array){
    $data = '';
    $ret = array();
    $hash = $array['hash'];
    unset($array['hash']);

    foreach($array as $key => $value){
        $data .= $key . $value;
        $ret[] = "$key=$value";
    }

    $h = new Crypt_HMAC(SECRET_KEY, 'sha1');
    if($hash != $h->hash($data)){
        return false;
    }else{
        return true;
    }
}

$array = array(
    'cause'=>'vars',
    'hash'=>'6350af376e25c3d6d1c41bc7e62b8b4b3448e317'
);

if(!verify_parameters($array)){
    die("Dweep! Somebody tampered with our parameters.\n");
}else{
    echo "Good guys, the do not touch our stuff!!";
}


